<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
   
      <el-form-item label="付款人" prop="acntName">
        <el-input
          v-model="queryParams.acntName"
          placeholder="请输入付款人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收款人" prop="toName">
        <el-input
          v-model="queryParams.toName"
          placeholder="请输入收款人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="摘要" prop="furInfo">
        <el-input
          v-model="queryParams.furInfo"
          placeholder="请输入摘要"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="交易日期" prop="txnDate">
        <el-date-picker clearable
          v-model="queryParams.txnDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择交易日期">
        </el-date-picker>
      </el-form-item>
     <!-- <el-form-item label="交易时间" prop="txnTime">
        <el-input
          v-model="queryParams.txnTime"
          placeholder="请输入交易时间"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
       <el-form-item label="流水号" prop="vchNum">
        <el-input
          v-model="queryParams.vchNum"
          placeholder="请输入流水号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="付款账号" prop="fkActAcn">
        <el-input
          v-model="queryParams.fkActAcn"
          placeholder="请输入付款账号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收款账号" prop="skActAcn">
        <el-input
          v-model="queryParams.skActAcn"
          placeholder="请输入收款账号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文件名称" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="输入日期" prop="inputDate">
        <el-date-picker clearable
          v-model="queryParams.inputDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择输入日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="凭证号码(票据号码)" prop="vouchNum">
        <el-input
          v-model="queryParams.vouchNum"
          placeholder="请输入凭证号码(票据号码)"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预留项4(子票区间，附言)" prop="reserve4">
        <el-input
          v-model="queryParams.reserve4"
          placeholder="请输入预留项4(子票区间，附言)"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:receipt:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:receipt:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:receipt:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:receipt:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="receiptList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="发生金额" align="center" prop="txnAmt" />
      <el-table-column label="余额" align="center" prop="avlBal" />
      <el-table-column label="付款人" align="center" prop="acntName" />
      <el-table-column label="收款人" align="center" prop="toName" />
      <el-table-column label="摘要" align="center" prop="furInfo" />
      <el-table-column label="交易日期" align="center" prop="txnDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.txnDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="流水号" align="center" prop="vchNum" />
      <el-table-column label="付款账号" align="center" prop="fkActAcn" />
      <el-table-column label="收款账号" align="center" prop="skActAcn" />
      <el-table-column label="文件名称" align="center" prop="fileName" />
      <el-table-column label="输入日期" align="center" prop="inputDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.inputDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="凭证号码(票据号码)" align="center" prop="vouchNum" />
      <el-table-column label="预留项4(子票区间，附言)" align="center" prop="reserve4" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- 新增：下载按钮 -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownload(scope.row)"
            v-hasPermi="['system:receipt:download']"
          >下载</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:receipt:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:receipt:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改电汇回执单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="发生金额" prop="txnAmt">
          <el-input v-model="form.txnAmt" placeholder="请输入发生金额" />
        </el-form-item>
        <el-form-item label="余额" prop="avlBal">
          <el-input v-model="form.avlBal" placeholder="请输入余额" />
        </el-form-item>
        <el-form-item label="付款人" prop="acntName">
          <el-input v-model="form.acntName" placeholder="请输入付款人" />
        </el-form-item>
        <el-form-item label="收款人" prop="toName">
          <el-input v-model="form.toName" placeholder="请输入收款人" />
        </el-form-item>
        <el-form-item label="摘要" prop="furInfo">
          <el-input v-model="form.furInfo" placeholder="请输入摘要" />
        </el-form-item>
        <el-form-item label="交易日期" prop="txnDate">
          <el-date-picker clearable
            v-model="form.txnDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择交易日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="流水号" prop="vchNum">
          <el-input v-model="form.vchNum" placeholder="请输入流水号" />
        </el-form-item>
        <el-form-item label="付款账号" prop="fkActAcn">
          <el-input v-model="form.fkActAcn" placeholder="请输入付款账号" />
        </el-form-item>
        <el-form-item label="收款账号" prop="skActAcn">
          <el-input v-model="form.skActAcn" placeholder="请输入收款账号" />
        </el-form-item>
        <el-form-item label="文件名称" prop="fileName">
          <el-input v-model="form.fileName" placeholder="请输入文件名称" />
        </el-form-item>
        <el-form-item label="输入日期" prop="inputDate">
          <el-date-picker clearable
            v-model="form.inputDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择输入日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="凭证号码(票据号码)" prop="vouchNum">
          <el-input v-model="form.vouchNum" placeholder="请输入凭证号码(票据号码)" />
        </el-form-item>
        <el-form-item label="预留项4(子票区间，附言)" prop="reserve4">
          <el-input v-model="form.reserve4" placeholder="请输入预留项4(子票区间，附言)" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listReceipt, getReceipt, delReceipt, addReceipt, updateReceipt,downloadReceiptFile } from "@/api/system/receipt"

export default {
  name: "Receipt",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 电汇回执单表格数据
      receiptList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        txnAmt: null,
        avlBal: null,
        acntName: null,
        toName: null,
        furInfo: null,
        txnDate: null,
        vchNum: null,
        fkActAcn: null,
        skActAcn: null,
        fileName: null,
        inputDate: null,
        vouchNum: null,
        reserve4: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询电汇回执单列表 */
    getList() {
      this.loading = true
      listReceipt(this.queryParams).then(response => {
        this.receiptList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        txnAmt: null,
        avlBal: null,
        acntName: null,
        toName: null,
        furInfo: null,
        txnDate: null,
        vchNum: null,
        fkActAcn: null,
        skActAcn: null,
        fileName: null,
        inputDate: null,
        vouchNum: null,
        reserve4: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加电汇回执单"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getReceipt(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改电汇回执单"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateReceipt(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addReceipt(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除电汇回执单编号为"' + ids + '"的数据项？').then(function() {
        return delReceipt(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },



    /** 下载文件 */
    handleDownload(row) {
    const fileName = row.fileName;
    if (!fileName) {
      this.$modal.msgWarning("文件名称为空，无法下载");
      return;
    }

    // 直接调用导入的downloadReceiptFile（不加this！）
    downloadReceiptFile(fileName)
      .then(response => {
        // 处理后端返回的二进制流（文件）
        this.handleBlobDownload(response, fileName);
      })
      .catch(error => {
        // 捕获下载错误
        this.$modal.msgError("下载失败：" + (error.msg || "未知错误"));
      });
    },
  handleBlobDownload(blob, fileName) {
      // 创建a标签（用于触发下载）
      const link = document.createElement("a");
      // 创建blob URL（指向二进制流）
      const url = URL.createObjectURL(new Blob([blob.data]));
      // 设置a标签属性
      link.href = url;
      link.download = fileName; // 下载的文件名
      // 隐藏a标签并添加到页面
      link.style.display = "none";
      document.body.appendChild(link);
      // 触发点击下载
      link.click();
      // 清理资源（避免内存泄漏）
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/receipt/export', {
        ...this.queryParams
      }, `receipt_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
